/*
 * Copyright © 2021 http://www.hn-szzy.com/ All rights reserved.
 */
package com.xjh.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjh.mapper.AclUserMapper;
import com.xjh.po.AclUserPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author： 徐建华
 * @date： 2022/2/13
 * @description：
 */

/**
 * UserDetailsService ：用户操作相关的接口类，当我们想要从数据库中查询用户的信息的时候需要实现实现此接口查询用户信息；
 */
@Service("passwordUserDetailsService")
public class PasswordUserDetailsService implements UserDetailsService {

    @Autowired
    private AclUserMapper aclUserMapper;

    @Override
    // UserDetails实体是官方的,包含了用户名、密码、权限
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据用户名查询数据库
        AclUserPO user = aclUserMapper.selectOne(Wrappers.<AclUserPO>lambdaQuery().eq(AclUserPO::getUsername, username));
        // 校验用户名是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        // 2.设置该用户的权限（这里直接写死，真实情况应该从数据库中获取）
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("h");

        // 3.返回给调用者一个user对象，该对象包含了该用户真实的用户名、密码、和权限
        return new User(user.getUsername(),
                new BCryptPasswordEncoder().encode(user.getPassword()),
                auths);
    }
}

